﻿using System.Collections.Generic;
using System.IO;
using Whisper.net;

namespace Armon.Lib.Media.Speech
{
    public class SpeechRecognition
    {
        private readonly WhisperFactory whisperFactory;
        private readonly WhisperProcessor whisperProcessor;
        private readonly List<SegmentData> segments;


        public SpeechRecognition(string modelPath)
        {
            this.segments = new List<SegmentData>();
            this.whisperFactory = WhisperFactory.FromPath(modelPath);
            this.whisperProcessor = this.whisperFactory.CreateBuilder()
               .WithLanguage("zh")
               .WithSegmentEventHandler(this.segments.Add)
               .Build();

        }

        public string Recognize(string targetPath)
        {
            this.segments.Clear();
            var txtResult = string.Empty;
            var fileStream = File.OpenRead(targetPath);
            //开始识别
            this.whisperProcessor.Process(fileStream);

            //识别结果处理
            foreach (var segment in segments)
            {
                txtResult += segment.Text;
            }
            this.segments.Clear();
            return txtResult;
        }
    }
}
